package com.yunxi.core.base;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.converts.MySqlTypeConvert;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.DbColumnType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

public class CodeGenerator {

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        System.out.println(projectPath);
        //在项目中生成
        //gc.setOutputDir(projectPath + "/src/main/java");

        gc.setOutputDir("F://test//");
        gc.setAuthor("Guan");
        gc.setOpen(false);
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        gc.setServiceName("%sService");
        gc.setControllerName("%sController");
        gc.setBaseResultMap(true);
        gc.setDateType(DateType.ONLY_DATE);
        gc.setSwagger2(true);
        gc.setIdType(IdType.INPUT);
        //是否覆盖文件
        gc.setFileOverride(true);
        //gc.setActiveRecord(true);// 不需要ActiveRecord特性的请改为false
        //gc.setEnableCache(false);// XML 二级缓存
        //gc.setBaseResultMap(true);// XML ResultMap
        //gc.setBaseColumnList(true);// XML columList
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://39.105.213.235:3306/dms?characterEncoding=utf-8&useSSL=false");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("passw0rd");
        dsc.setDbType(DbType.MYSQL);

        dsc.setTypeConvert(new MySqlTypeConvert(){
            // 自定义数据库表字段类型转换【可选】
            public DbColumnType processTypeConvert(GlobalConfig gc,String fieldType) {
                System.out.println("转换类型：" + fieldType);
                // 注意！！processTypeConvert 存在默认类型转换，如果不是你要的效果请自定义返回、非如下直接返回。
                return (DbColumnType) super.processTypeConvert(gc,fieldType);
            }
        });
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        //模块名称
        //命令行输入
        //pc.setModuleName(scanner("模块名"));
        //pc.setController("controller");
        pc.setParent("com.yunxi");
        pc.setModuleName("sys");
        pc.setEntity("model");//设置bean的包
        pc.setMapper("dao");

        mpg.setPackageInfo(pc);

        // 自定义配置 自定义全局参数
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
                map.put("jinhao", "#");
                map.put("duole", "$");
                this.setMap(map);
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输入文件名称

                //Map map = mpg.getTemplateEngine().getObjectMap(tableInfo);
                //System.out.println(map);
                return "F://test" + "/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });

        focList.add(new FileOutConfig("/templates/api.js.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return "F://test" + "/views/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + ".js";
            }
        });

        focList.add(new FileOutConfig("/templates/main.vue.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return "F://test" + "/views/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "_main.vue";
            }
        });

        focList.add(new FileOutConfig("/templates/common.vue.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
                return "F://test" + "/views/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "_common.vue";
            }
        });

        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);//表名策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//字段名策略
        //strategy.setSuperEntityClass("com.baomidou.ant.common.BaseEntity");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        //strategy.setSuperControllerClass("com.baomidou.ant.common.BaseController");
        //需要生成的表名
        strategy.setInclude(scanner("表名"));//new String[] { "sys_user","car_staff" }
        //公共字段
        //strategy.setSuperEntityColumns("id");
        //自定义mapper
        //strategy.setSuperMapperClass("com.baomidou.demo.TestMapper");
        //自定义service父类
        //strategy.setSuperServiceClass("com.baomidou.demo.TestService");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());

        mpg.execute();
    }
}